import 'package:ait/entity/ait_span_entity.dart';
import 'package:ait/utils/f_text_editing_contronller.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Ait',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  FTextEditingController _controller = FTextEditingController();
  FocusNode _focusNode =FocusNode();
  String uploadText = "";

  @override
  void initState() {
    _controller.text = "";
    _controller.textSize = _controller.text.length;
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      _focusNode.requestFocus();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("ait people"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              width: double.infinity,
              padding: EdgeInsets.only(left: 10.0, right: 10.0),
              margin: EdgeInsets.all(10.0),
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(10.0)),
                  border: Border.all(
                    color: ThemeData.light().dividerColor,
                  ),
                  color: Colors.grey[200]),
              child: TextField(
                maxLines: 10,
                controller: _controller,
                focusNode: _focusNode,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                  border: InputBorder.none,
                  hintText: "请输入",
                  hintStyle: TextStyle(fontSize: 14, color: Colors.grey),
                ),
                onChanged: onTextChanged, // 当光标在文字块后方时，才处理，否则不做处理，走正常删除
              ),
            ),
            SizedBox(
              width: double.infinity,
              child: TextButton(
                onPressed: () {
                  addAit();
                },
                child: Text(
                  "添加@文字块",
                  style: TextStyle(color: Colors.white),
                ),
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.red),
                ),
              ),
            ),
            SizedBox(
              width: double.infinity,
              child: TextButton(
                onPressed: () {
                  addEvent();
                },
                child: Text(
                  "添加#文字块",
                  style: TextStyle(color: Colors.white),
                ),
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.red),
                ),
              ),
            ),
            SizedBox(
              width: double.infinity,
              child: TextButton(
                onPressed: () {
                  add$Span();
                },
                child: Text(
                  "添加\$文字块",
                  style: TextStyle(color: Colors.white),
                ),
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.red),
                ),
              ),
            ),
            SizedBox(
              width: double.infinity,
              child: Text(
                uploadText,
                style: TextStyle(color: Colors.black),
              ),
            ),
            SizedBox(
              width: double.infinity,
              child: TextButton(
                onPressed: () {
                  setState(() {
                    uploadText = _controller.getUploadFormatText();
                  });
                  _controller.parseIntoEditableText(
                      "智选{[@tip,10]}车业务提供智能系统及部件解{[#event,15]}决方案的独{[\$event,15,55]}立新公司");
                },
                child: Text(
                  "获取上传服务端的文本",
                  style: TextStyle(color: Colors.white),
                ),
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.red),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  void onTextChanged(String newText) {
    int selectionStart = _controller.selection.start;
    if (newText.isNotEmpty && selectionStart > 0) {
      String mentionChar = newText[selectionStart - 1];
      if (mentionChar == '@') {
        // 删除刚刚输入的@
        _controller.deleteText(1);
        // print("输入@");
        // Navigator.push(context, MaterialPageRoute(builder: (context) => TableCalendarPage()));
        addAit();
      } else if (mentionChar == '#') {
        // 删除刚刚输入的#
        _controller.deleteText(1);
        // Navigator.push(context, MaterialPageRoute(builder: (context) => TableCalendarPage()));
        addEvent();
      }
    }
  }

  // 这里就是模拟页面跳转选择之后，插入文字块
  void addAit() {
    int id = 10;
    String name = "Bear";
    // 第一个参数就是拼接成@张三 格式，建议后面加空格，原生安卓版不加会有问题
    // 第二个参数就是提交给后端的格式，可以自己自定义
    SpanEntity span =
        SpanEntity("@${name} ", "{[@$name,$id]}", color: Colors.blue);
    _controller.insertSpan(span);
  }

  void addEvent() {
    int id = 9999;
    int accId = 6556;
    String name = "事件";
    SpanEntity span =
        SpanEntity("#${name} ", "{[#$name,$id,$accId]}", color: Colors.red);
    _controller.insertSpan(span);
  }

  void add$Span() {
    int id = 555;
    String name = "公司";
    SpanEntity span =
        SpanEntity("\$${name} ", "{[\$$name,$id]}", color: Colors.orange);
    _controller.insertSpan(span);
  }
}
